/**
 * 
 * @param {*} dataUrl string
 * @returns 将dataurl转成Blob
 */
export const dataUrlToBlob = (dataUrl) => {
    const _array = dataUrl.split(',');
    const _mimeType = _array[0].match(/:(.*?);/)[1];
    const _bytes = window.atob(_array[1]);
    let _length = _bytes.length;
    const _uint8Array = new Uint8Array(_length);
    while (_length) {
      _length -= 1;
      _uint8Array[_length] = _bytes.charCodeAt(_length);
    }
    return new Blob([_uint8Array], { type: _mimeType });
  };
  
  /**
   * 
   * @param {*} dataUrl 
   * @returns 将dataurl转成base64
   */
  export const dataUrlToBase64 = (dataUrl) => {
    const _array = dataUrl.split(',');
    const base64 = _array[1];
    return base64;
  };
  
  /**
   * 
   * @param {*} file 
   * @param {*} callback 
   * 将文件转成dataurl
   */
  export const fileToDataUrl = (file, callback) => {
    const _fileReader = new FileReader();
    _fileReader.onload = (event) => {
      const __fileReader = event.target;
      callback(__fileReader.result);
    };
    _fileReader.readAsDataURL(file);
  };


/**
 * 文件选择
 *  option= {
    accept:'.txt.pdf' 选择文件的后缀名
    capture?:是否开启摄像头
    multiple?:是否多选
  },
 * {function} complete 回调事件
 */
  let element = null
  export const filePicker = (
    callback,
    option = {}
  ) => {
    element = document.createElement('input')
    element.setAttribute('type', 'file')
    const { accept = '*/*', capture, multiple } = option || {}
    element.setAttribute('accept', accept)
    if (capture) {
      element.setAttribute('capture', capture)
    }
    if (multiple) {
      element.setAttribute('multiple', 'multiple')
    }
    element.style.display = 'none'
    element.addEventListener(
      'change',
      (event) => {
        element = null
        const _element = event.target
        if (_element.value) {
          const { files } = _element
          const fileObjs = []
          for (let i = 0, { length } = files; i < length; i += 1) {
            const file = files[i]
            fileObjs.push({
              file
            })
          }
          callback(fileObjs)
        }
      },
      true
    )
    element.click()
  }
  